package org.chenzhi.mvp.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import org.chenzhi.mvp.SimpleMVP;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author orange
 * @function MVP基础类
 */

public class BasePresenter <V extends BaseView> {
    protected Map<String, Object> params;
    private WeakReference<V> mReference = null;

    public BasePresenter() {
        getIntentData();
    }

    public void attach(V view) {
        mReference = new WeakReference<>(view);
    }

    public void detach() {
        if (null != mReference) {
            mReference.clear();
            mReference = null;
        }
    }

    public boolean isAttach() {
        return null != mReference && null != mReference.get();
    }

    public V getView() {
        if (isAttach()) {
            return mReference.get();
        }

        return null;
    }

    /**
     * 获取context，需要注意可能会有空异常发生
     * !important 该API在控件没有注册或者栈顶没有元素的时候返回空
     * @return 栈顶Activity的上下文
     */
    protected Context getContext() {

        if (!SimpleMVP.getInstance().isInstalled()) {
            return null;
        }

        try {
            Field topActivityFiedld = SimpleMVP.class.getDeclaredField("topActivity");
            topActivityFiedld.setAccessible(true);

            return (Activity) topActivityFiedld.get(SimpleMVP.getInstance());
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 获取Intent传递过来的参数
     */
    private void getIntentData() {

        if (params == null) {
            params = new HashMap<>();
        }

        Intent intent = ((Activity) getContext()).getIntent();
        Bundle mBundle = intent.getExtras();
        for (String key : mBundle.keySet()) {
            Object value = mBundle.get(key);
            params.put(key, value);
        }
    }
}
